﻿using CRM.Models;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using System.Collections.Generic;
using CRM.Enums;

namespace CRM.Services
{
    public class OemService : BaseService
    {
        private readonly MyDbContext _dbContext;

        public OemService(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public Oem GetInfo(int id)
        {
            return _dbContext.Oem.FirstOrDefault(m => m.Id == id);
        }


        /// <summary>
        /// 获取当前公司拥有全部OEM
        /// </summary>
        public record ChooseData(int Id, string Name);

        public List<ChooseData> GetOwnOems(User userData)
        {
            //获取全部oem信息
            var Oems = _dbContext.Oem.Where(i => i.State == States.ENABLE).Select(n => new ChooseData
            (
                n.Id,
                n.Name
            )).ToList();

            if (userData.Type == User.Types.Super || userData.Type == User.Types.Admin)
            {
                //超管、管理员
                return Oems;
            }

            //分配贴牌
            var OemIds = _dbContext.OemCompany.Where(i => i.CompanyId == userData.CompanyId).ToList().Select(m => m.OemId);

            List<ChooseData> OwnOems = new List<ChooseData>();
            Oems.ForEach((r) =>
            {
                if (OemIds.Contains(r.Id)) OwnOems.Add(r);
            });

            return OwnOems;
        }

        /// <summary>
        /// 获取当前域名前缀对应的oem
        /// </summary>
        /// <returns>当前oem</returns>
        public Task<Oem> GetCurrentOem()
        {
            if (Request.Host.Host == "localhost")
            {
                return _dbContext.Oem.FirstOrDefaultAsync(o => o.Id ==6);
            }
            var domainSuffix = Request.Host.Host.Split('.')[0] + '.';
            return _dbContext.Oem.FirstOrDefaultAsync(m => m.Domain.StartsWith(domainSuffix));
        }
    }
}